import requests,re,json,time,random,os
from pyquery import PyQuery as pq
from urllib import request
from http import cookiejar

def getAgent():
	user_agents = [
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
    'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7',
    'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0',
	]
	import random
	agent = random.choice(user_agents) # 随机获取一个浏览器用户信息
	return agent


#获取京东购物车页面
def getPage(headers):
	url='https://cart.jd.com/cart.action'
	res=requests.get(url,headers=headers,verify=False)
	return res.content.decode('utf8')

#根据id查询店铺名称信息
def getvenderIds(venderIds,headers):
	url='https://cart.jd.com/getVenders.action'
	data={
		't': 0,
		'venderIds': venderIds,
		'random': random.random()
	} 
	res=requests.post(url,headers=headers,data=data,verify=False)
	return json.loads(res.content.decode('utf8'))


def parsePage(content,headers):
	doc=pq(content)
	cartList=doc('.cart-item-list')
	#店铺id
	venderIds=doc('#venderIds').val()
	JD_shoppingCar={
		'goodNum':doc('.toolbar-right').find('.amount-sum em').html(),
		'payMoney':doc('.toolbar-right').find('.sumPrice em').html(),
		'shopList':[]
	}
	shopList = []
	for shop in cartList.items():
		storeInfo={
		'storeName':'',
		'goodList':[]
		}
		shop_id = shop.find('.cart-tbody').attr('id')
		if shop_id == 'vender_8888':
			storeInfo['storeName']='京东自营'
		else:
			#ajax动态获取店铺信息
			shop_info=getvenderIds(venderIds,headers)['sortedWebVenderResult']['orderPopInfos']
			for info in shop_info:
				#根据id 动态匹配店铺信息
				if shop_id == 'vender_'+str(info.get('venderId',None)):
					storeInfo['storeName']=info.get('shopName','旗舰店名称不存在')
					break
		goodItems = shop.find('.item-list .item-item')
		for goods in goodItems.items():
			goodsObj={
				'goodImg':'https:'+goods.find('.p-img a').attr('href'),
				'goodName':' '.join(goods.find('.p-name').text().split('\n')),
				'extendInfo':goods.find('.p-extend').text(),
				'props':' '.join(goods.find('.p-props').text().split('\n')),
				'singlePrice':goods.find('.p-price strong').text(),
				'priceDiscount':' '.join(goods.find('.p-price strong').siblings().text().split('\n')),
				'goodNum':goods.find('.p-quantity input').val(),
				'totalPrice':goods.find('.p-sum strong').text(),
			}
			storeInfo['goodList'].append(goodsObj)
		shopList.append(storeInfo)
	JD_shoppingCar['shopList'] = shopList
	JD_shoppingCar=json.dumps(JD_shoppingCar,ensure_ascii=False)
	return JD_shoppingCar



def writeContent(content):
	with open('./jd.json','a',encoding='utf8') as f:
		f.write(content)
		f.close()


if __name__ == '__main__':
	headers={
	'Referer': 'https://cart.jd.com/cart.action',
	'User-Agent': getAgent()
	}
	#choose = str(input('是否加载本地cookie信息？ y or n or exit ：\n'))
	'''
	print('正在模拟发送请求：','https://cart.jd.com/cart.action')
	#判断本地cookie文件是否存在
	cookie = cookiejar.CookieJar()
	handler = request.HTTPCookieProcessor(cookie)
	opener = request.build_opener(handler)
	#打开网页地址获取 cookie信息
	res =opener.open('https://cart.jd.com/cart.action')
	cookieContext =''
	for item in cookie:
		cookieContext = cookieContext + item.name + '=' + item.value + ';'
	print('----',cookieContext)
	headers['Cookie'] = cookieContext
	'''
	ck = 'unpl=V2_ZzNtbUNWExxwXU4Gch5cBGIDQVsSX0YRcVsUB3JJCFFiA0FeclRCFXwUR1NnGl8UZwIZXkpcRhVFCHZXfBpaAmEBFl5yBBNNIEwEACtaDlwJBBpURFFGEXIKT1dLKV8FVwMTbUFXQx19DU9TehpsNWAzIm1KU0IQfA12VUsYbEczXxBfQ1BDWHYIRlxzHFUCZgAiXHJU; ipLoc-djd=1-72-2799-0; __jdv=122270672|baidu-search|t_262767352_baidusearch|cpc|69877456382_0_00a84d9c861041b7a9455bcb8aee41b2|1529634578821; shshshfpa=e58b4829-7785-0761-fa76-c868bd165291-1529634582; shshshfpb=2bd87001f9c6c4c4b9393ff5f981c40d55b28ff1b931fd6446f2c5f1c1; 3AB9D23F7A4B3C9B=ITJTDQH6BOJYW56OQ3QSFF2SR3JGXKSEHRIKOCSNIRVK2UQ6SG2K3V5K3L57454SQWJYY6MWP6V4HF2AM7YRWRGR7E; user-key=0778ff74-a7f0-478c-865c-7cf61b4d07b7; PCSYCityID=904; cart-main=xx; cd=0; shshshfp=e92569302d35b117d6743de8fc3c7d27; __jda=122270672.2119948602.1527673952.1530493790.1530583747.5; __jdc=122270672; cn=8; __jdu=2119948602; shshshsID=dbe2dd81d6274d7dd1f9f82d7742964a_7_1530586127251; __jdb=122270672.7.2119948602|5.1530583747'
	headers['Cookie'] = ck
	pageContent = getPage(headers)
	JD_shoppingCar = parsePage(pageContent,headers)
	writeContent(JD_shoppingCar)